/**
 * Created with JetBrains WebStorm.
 * User: fancylou
 * Date: 13-6-14
 * Time: 下午9:34
 * Description: 西瓜
 */

var watermelonSprite = cc.Sprite.extend({

    radius:40,//碰撞半径
    velocity:null,

    ctor:function(){
        this._super();
        this.initData();
    },

    initData:function(){
        this.initWithFile(s_watermelon);
        this.setPosition(cc.p(144,176));
        this.velocity = cc.p(100,0);
    },

    update:function(dt){
        this.setPosition(cc.pAdd(this.getPosition(), cc.pMult(this.velocity, dt)));
        this.checkHitEdge();
    },

    beginRotate:function(){//开始旋转
        var rotate = cc.RotateBy.create(1, 360);//1秒钟转360度
        var rep = cc.RepeatForever.create(rotate);//重复执行rotate
        this.runAction(rep);//执行动作
    },

    stopRotate:function(){//停止旋转
        this.stopAllActions();
    },
    //检查边界碰撞
    checkHitEdge: function () {
        var pos = this.getPosition();
        var contentSize = this.getContentSize();
        var winSize = cc.Director.getInstance().getWinSize();
        if (pos.x > winSize.width - this.radius) {//右边界
            this.velocity.x *= -1;//改变水平速度方向
        }
        if (pos.x < this.radius) {//左边界
            this.velocity.x *= -1;//改变水平速度方向
        }
        if (pos.y <= this.radius) {//下边界
            this.velocity.y *= -1;
        }
        if (pos.y >= winSize.height - this.radius) {//上边界
            this.velocity.y *= -1;
        }
    },

    //碰撞检测
    collide: function (gameObject) {
        var hit = false;
        var distance = cc.pDistance(this.getPosition(), gameObject.getPosition());//两者之间的距离
        //计算碰撞角度，往反方向弹回去
        if (distance <= this.radius + gameObject.radius) {
            hit = true;
            //计算碰撞角度
            var hitAngle = cc.pToAngle(cc.pSub(gameObject.getPosition(), this.getPosition()));
            var scalarVelocity = cc.pLength(this.velocity);
            this.velocity = cc.pMult(cc.pForAngle(hitAngle), scalarVelocity);
            //反方向移动
            this.velocity.x *=-1;
            this.velocity.y *=-1;
        }
        return hit;
    },

    collideWall:function(flag){
        if(flag){
            //反方向移动
            this.velocity.x *=-1;
            this.velocity.y *=-1;
        }
    }
});
